package com.jin.webvideo.config.filter.access.handler;

import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.config.filter.access.AccessControl;
import com.jin.webvideo.config.filter.access.GlobalStore;
import com.jin.webvideo.entity.ForbidRecord;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.entity.User;
import com.jin.webvideo.service.AccessServer;
import com.jin.webvideo.util.SimpleTemplateParser;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.base.util.SystemInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户黑名单处理
 */
public class UserAccessHandler implements AccessHandler {
    @Autowired
    private AccessServer accessServer;
    @Autowired
    private SimpleTemplateParser parser;
    public UserAccessHandler() {

    }
    @Override
    public boolean handle(GlobalStore globalStore, SessionStore store, HttpServletRequest request, AccessControl.Access access, HandlerChain handlerChain) {
        if (store == null || store.getUser() == null) {
            return handlerChain.doHandle(access, globalStore, request, store);
        }
        User user = store.getUser();
        String uri = request.getRequestURI();
        List<ForbidRecord> records = accessServer.findRecordByUser(user.getAccount(), SystemInfo.nowSecond(), ForbidRecord.FORBID_TYPE_PATH);
        // 查找path封禁记录
        ForbidRecord record = CollectionsUtil.first(records, (r) -> StringUtil.match(r.getVal(), uri));
        if (record == null) {
            return handlerChain.doHandle(access, globalStore, request, store);
        }
        parser.setVariables(BeanMap.create(record));
        String msg = parser.getValue(record.getInformation(), String.class);
        AccessControl.Access.forbid(access, 403, msg);
        return true;
    }

    @Override
    public int order() {
        return Integer.MIN_VALUE + 1;
    }
}
